package apj.demo.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import apj.demo.dao.UserDao;
import apj.demo.model.User;
import apj.demo.util.JDBCUtil;

public class UserDaoImpl implements UserDao {
	private final String FIND_BY_ID = "select * from user where user_id = ?";
	private final String FIND_BY_ALL ="select * from user ";
	private final String SAVE ="insert user (user_id,password,position)values(?,?,?)";
	
	@Override
	public User findByID(String id) throws SQLException{
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		User user = null;
		try{
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(FIND_BY_ID);
			ps.setString(1,id);
			rs = ps.executeQuery();
			while(rs.next()){
				user = new User();
				user.setUserId(rs.getString("user_id"));
				user.setPassword(rs.getString("password"));
				user.setPosition(rs.getString("position"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCUtil.close(rs);
			JDBCUtil.close(ps);
			JDBCUtil.close(conn);
		}
		return user;
	}

	@Override
	public ArrayList<User> findByAll() throws SQLException{
		
		ArrayList<User> users = new ArrayList<User>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try{
			User user = null;
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(FIND_BY_ALL);
			rs = ps.executeQuery();
			while(rs.next()){
				user = new User();
				user.setUserId(rs.getString("user_id"));
				user.setPassword(rs.getString("password"));
				user.setPosition(rs.getString("position"));
				
				users.add(user);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCUtil.close(rs);
			JDBCUtil.close(ps);
			JDBCUtil.close(conn);
		}
		return users;
	}

	@Override
	public void save(User user) throws SQLException {
		Connection conn = null;
		PreparedStatement ps = null;
		try{
			conn = JDBCUtil.getConnection();
			ps = conn.prepareStatement(SAVE);
			ps.setString(1, user.getUserId());
			ps.setString(2, user.getPassword());
			ps.setString(3, user.getPosition());
			ps.executeUpdate();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			JDBCUtil.close(ps);
			JDBCUtil.close(conn);
		}
				
	}

}
